<?php

namespace app\api\controller;

use addons\shopro\model\commission\DivisionLog;
use addons\shopro\model\User as UserModel;
use addons\shopro\model\Order as OrderModel;
use app\admin\controller\shopro\order\Order;
use app\admin\model\ShoproUserWithdraw;
use app\common\controller\Api;
use app\common\library\Auth;
use app\common\logic\UserLevelLogic;
use app\common\model\MoneyLog;

class Bonus extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    /*
     * 首页
     */
    public function index()
    {
        $model = new DivisionLog();
        $user = $this->auth->getUserinfo();
        if($user['member_level'] < 0){
            $level_name = '暂无等级';
        }else{
            $level_name = UserLevelLogic::getLevelNameById($user['member_level']);
        }
        $bankInfo = \addons\shopro\model\UserBank::info('bank');
        if($bankInfo['card_no'] == '****'){
            $bankInfo['card_no'] = '';
        }
        $user['withdraw_text'] = '';
        $user['is_withdraw'] = 0;
        //if ($user['member_level'] >= 3) {
            $first_team_consume = $this->getFirstTeamConsumeMoney($user['id']);
            $withdraw_config_amount = config('site.withdraw_min_consume');
//            if ($first_team_consume < $withdraw_config_amount) {
//                $diff = $withdraw_config_amount - $first_team_consume;
//                //$withdraw_text = sprintf('一级团队还差%s达到%s万', $diff, $withdraw_config_amount / 10000);
//                $withdraw_text = sprintf('一级团队还差%s达到%s', $diff, $withdraw_config_amount);
//            } else {
//                $withdraw_text = sprintf('一级团队消费总额%s', $first_team_consume);
//            }
            $user['withdraw_text'] = sprintf('%s/%s', $first_team_consume, $withdraw_config_amount);;
            $withdraw_day = config('site.withdraw_day');

            if (date('d') == $withdraw_day && $first_team_consume >= $withdraw_config_amount) {
                $user['is_withdraw'] = 1;
            }
        //}


        $data = [];
        $data['user_info'] = $user;
        $data['bank_info'] = $bankInfo;
        $data['level_name'] = $level_name;
        //总收益
        $sum_price = $model->where('uid = '.$user['id'])->sum('commission_price');
        //if(empty($sum_price)) $sum_price = 0;
        $data['commission_price'] = $sum_price;
        //代转账佣金
        $sum_price = $model->where('uid = '.$user['id'].' and is_com = 0')->sum('commission_price');
        //if(empty($sum_price)) $sum_price = 0;
        $data['wait_commission_price'] = $sum_price;
        $this->success('请求成功',$data);
    }

    private function getFirstTeamConsumeMoney($uid)
    {
        $ids = UserModel::where(['parent_user_id' => $uid, 'status' => 'normal'])->column('id');
        $last_withdraw_time = ShoproUserWithdraw::where('user_id', $uid)
            ->order('id', 'desc')
            ->where('status', '>=', 0)
            ->value('createtime', 0);
        return OrderModel::whereIn('user_id', $ids)
            ->where('paytime', '>', $last_withdraw_time)
            ->where('pay_fee', '<>', 29.9) //排除优惠券购买的
            ->payed()
            ->sum('total_fee');
    }

    private function getWithdrawMoney()
    {
        $user = $this->auth->getUser();
        $member_level = $user['member_level'];
        if ($member_level < 3) {
            return 0;
        }
        //提现比例
        $arr = [3 => 5, 4 => 10, 5 => 15];
        $ratio = ($arr[$member_level] ?? 0) * 0.01;
        if (empty($ratio)) return 0;
        $first_team_consume = $this->getFirstTeamConsumeMoney($user['id']);
        return bcmul($first_team_consume, $ratio, 2);
    }
    //获取分销可提现金额
    public function withdraw_money()
    {
        $this->success('成功',$this->getWithdrawMoney());
    }
    //分销提现
    public function withdraw()
    {
        $user = $this->auth->getUser();
        $member_level = $user['member_level'];
        if ($member_level < 3) {
            $this->error('当前等级不可提现');
        }
        $first_team_consume = $this->getFirstTeamConsumeMoney($user['id']);
        $withdraw_config_amount = config('site.withdraw_min_consume');
        $withdraw_day = config('site.withdraw_day');
        if (date('d') != $withdraw_day || $first_team_consume < $withdraw_config_amount) {
            $this->error('不满足提现条件');
        }
        $money = $this->getWithdrawMoney();
        if ($money <= 0) {
            $this->error('可提现金额不足');
        }
        $res = ShoproUserWithdraw::create([
            'user_id' => $user['id'],
            'level_id' => $member_level,
            'team_amount' => $first_team_consume,
            'money' => $money,
            'apply_sn' => ShoproUserWithdraw::getSn($user['id']),
        ]);
        if ($res->id) {
            $this->success('申请成功');
        } else {
            $this->error('申请失败');
        }
    }

    /*
     * 我的团队
     */
    public function myTeam()
    {
        $auth = \app\common\library\Auth::instance();
        $auth->setAllowFields(['id', 'username', 'nickname', 'mobile', 'avatar', 'score', 'birthday', 'money', 'group', 'group_id', 'verification', 'child_user_count', 'child_user_count_1', 'child_user_count_2', 'total_consume', 'member_level']);
        $user = $auth->getUserinfo();

        // 获取下级直推团队用户信息
        //$nextUserTeam = UserModel::where(['parent_user_id' => $user['id'], 'status' => 'normal'])->column('id, child_user_count_2');
        //$child_user_count_3 = array_sum(array_column($nextUserTeam, 'child_user_count_2'));
        $one = UserModel::where(['parent_user_id' => $user['id'], 'status' => 'normal'])->field('id')->select();
        $data = [];
        $one_ids = array_column($one,'id');

        $two = UserModel::where(['parent_user_id' => ['in',$one_ids], 'status' => 'normal'])
            ->field('id')
            ->select();
        $two_ids = array_column($two,'id');
//        $three = UserModel::where(['parent_user_id' => ['in',array_column($two,'id')], 'status' => 'normal'])
//            ->field('id')
//            ->select();
        $one_consume = $this->getTeamConsumeMoney($one_ids);
        $two_consume = $this->getTeamConsumeMoney($two_ids);
        $data['all'] = count($one) + count($two);
        $data['all_consume'] = $one_consume + $two_consume;
        $data['one'] = count($one);
        $data['one_consume'] = $one_consume;
        $data['two'] = count($two);
        $data['two_consume'] = $two_consume;
//        $data['three'] = count($three);
        $data['three'] = 0;
        $this->success('请求成功',$data);
    }

    private function getTeamConsumeMoney($ids)
    {
        return OrderModel::whereIn('user_id',$ids)
            ->payed()
            ->sum('total_fee');
    }

    /*
     * 佣金明细
     */
    public function commissionList()
    {
        $type = input('type');//0=全部1=待入账2=已入账
//        $day = input('day',date('Y-m-d'));

//        $startTime = strtotime($day);
//        $endTime = strtotime($day) + 86399;

        $where = [
            'uid'=>$this->auth->id,
//            'createtime'=>['between',"$startTime,$endTime"]
        ];
        if($type == 1){
            $where['is_com'] = 0;
        }elseif ($type == 2){
            $where['is_com'] = 1;
        }

        $model = new DivisionLog();

        $data = $model::where($where)->order('createtime desc')->paginate(10);

        $sum =  $model::where('uid',$this->auth->id)->sum('commission_price');

        $this->success('请求成功',compact('data','sum'));
    }

    /*
     * 分销订单
     */
    public function commissionOrder()
    {
        $type = input('type');//0=全部1=已计入

        $where = [
            'uid'=>$this->auth->id
        ];
        if(!empty($type)){
            $where['is_com'] = 0;
        }
        $model = new DivisionLog();
        $data = $model::where($where)->order('createtime desc')->paginate(10);
        $order_num = $model::where('uid',$this->auth->id)->count();
        $order_price = $model::where('uid',$this->auth->id)->sum('commission_price');
        $this->success('请求成功',compact('data','order_num','order_price'));
    }

    /*
     * 我的海报
     */
    public function getMyImage()
    {
        $image = request()->domain().'/addons/shopro/wechat/wxacode?scene='.$this->auth->id.'&path=pages/index/index';
        $this->success('请求成功',compact('image'));
    }
}
